package com.submit.demo.service.impl;

import cn.hutool.json.JSONObject;
import com.submit.demo.config.MinIOProperties;
import com.submit.demo.dto.FilterSubmitterParam;
import com.submit.demo.model.SubTask;
import com.submit.demo.model.Task;
import com.submit.demo.model.Word;
import com.submit.demo.repository.SubTaskRepository;
import com.submit.demo.repository.TaskRepository;
import com.submit.demo.service.ProcessService;
import com.submit.demo.service.SubTaskService;
import com.submit.demo.util.MinIOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubTaskServiceImpl implements SubTaskService {
    @Autowired
    private SubTaskRepository subTaskRepository;

    @Autowired
    private MinIOProperties minIOProperties;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private ProcessService processService;


    @Override
    public Integer impSubTasks(String tid, List<String> sids) {
        List<SubTask> list = new ArrayList<>();
        for(String sid : sids){
            SubTask subTask = new SubTask();
            subTask.setTid(tid);
            subTask.setSid(sid);
            subTask.setStatus(0);
            list.add(subTask);
        }
        subTaskRepository.insert(list);
        Task task = taskRepository.findTaskById(tid);
        return 1;
    }

    @Override
    public Integer upload(String sid, String tid, MultipartFile[] files) {
        Task task = taskRepository.findTaskById(tid);
        SubTask subTask = subTaskRepository.findSubTaskBySidAndTid(sid, tid);
        subTask.setStatus(1);
        if(subTask.getWords() == null){
            subTask.setWords(new ArrayList<>());
        }
        List<Word> list = new ArrayList<>();
        for(MultipartFile word : files){
            Word w = new Word();
            String name = word.getOriginalFilename();
            w.setWord(name);
            w.setSubTime(new Date());
            list.add(w);
            try {
                MinIOUtil.upload(task.getTitle(), sid + "/" + name, word.getInputStream(), word.getSize());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        subTask.getWords().addAll(list);
        subTaskRepository.save(subTask);
        processService.record(tid, "提交了任务: " + task.getTitle());
        return 1;
    }

    @Override
    public SubTask findOne(String sid, String tid) {
        return subTaskRepository.findSubTaskBySidAndTid(sid, tid);
    }

    @Override
    public Integer update(FilterSubmitterParam param) {
        if(param.getSids() == null || param.getSids().size() <= 0) return 0;
        List<SubTask> list = subTaskRepository.findAllByTid(param.getTid());
        if(list == null || list.size() <= 0){
            impSubTasks(param.getTid(), param.getSids());
        }
        List<String> originList = list.stream().map(SubTask::getSid).collect(Collectors.toList());
        List<String> removeList = new ArrayList<>(originList);
        removeList.removeAll(param.getSids());
        log.info("移除人员: " + removeList);
        List<String> commonList = new ArrayList<>(originList);
        commonList.retainAll(param.getSids());
        param.getSids().removeAll(commonList);
        log.info("新增人员: " + param.getSids());
        impSubTasks(param.getTid(), param.getSids());
        if(removeList.size() > 0){
            Task task = taskRepository.findTaskById(param.getTid());
            List<String> objects = new ArrayList<>();
            Query query = new Query(Criteria.where("tid").is(param.getTid()).and("sid").in(removeList));
            List<SubTask> removeSubTasks = mongoTemplate.find(query, SubTask.class);
            removeSubTasks.forEach(item -> {
                JSONObject jsonObject = new JSONObject(item);
                log.info("删除: \n" + jsonObject.toStringPretty());
                if(item.getWords() != null && item.getWords().size() > 0) {
                    item.getWords().forEach(word -> {
                        objects.add(item.getSid() + "/" + word.getWord());
                    });
                }
            });
            MinIOUtil.deleteWords(task.getTitle(), objects);
            subTaskRepository.deleteAll(removeSubTasks);
        }
        Task task = taskRepository.findTaskById(param.getTid());
        processService.record(param.getTid(), "更新了任务: " + task.getTitle() + "的提交人名单");
        return 1;
    }
}
